﻿/*
 * @author Lee 
 * Time: 20180403 
 * Abstract: SharePoint API的二次封装
 */

using Microsoft.SharePoint;
using System;


namespace SharePointHelper.DLL.SSOM
{
    public class UsersAndGroups
    {
        #region 移除某个站点下的某个用户组
        /// <summary>
        /// 移除某个站点下的某个用户组
        /// </summary>
        /// <param name="siteURL"></param>
        /// <param name="webName">MyGroup</param>
        /// <param name="groupName">TestSubSite</param>
        public static void removeGroupsOnWeb(string siteURL, string webName, string groupName)
        {
            SPSite spSite = new SPSite(siteURL);
            SPWeb spWeb = spSite.OpenWeb(webName);
            SPGroupCollection groupCollection = spWeb.Groups;
            groupCollection.Remove(groupName);
            spWeb.Dispose();
        }
        #endregion

        #region 在Site Collection Group中添加User
        /// <summary>
        /// 在Site Collection Group中添加User
        /// </summary>
        /// <param name="spWeb"></param>
        /// <param name="groupName"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public static int addUserToGroup(SPWeb spWeb, string groupName, SPUser user)
        {         
            SPGroupCollection groupCollection = spWeb.SiteGroups;
            SPGroup group = groupCollection[groupName];
            SPUserCollection users=group.Users;
            
            try{
                SPUser oUser=users[user.LoginName];
                return 0;//the group has user
            }catch(Exception e){
                //the group doesn't has user
                group.AddUser(user);
                return 1;
            }                  
        }
        #endregion

        #region 根据登录名获取用户
        /// <summary>
        /// 根据登录名获取用户
        /// </summary>
        /// <param name="siteURL"></param>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public static SPUser getUserByLoginName(String siteURL, string loginName)
        {
            SPSite spSite = new SPSite(siteURL);
            SPWeb web = spSite.RootWeb;

            /*
                For SharePoint Online or on-premise forms authentication, use the below login name format:
                i:0#.f|membership|user@domain.com

                For SharePoint 2013 on-premise Windows authentication, use the below login name format:
                i:0#.w|domain\user

                For SharePoint 2013 on-premise SAML based authentication, use the below login name format:
                ?i:05:t|adfs with roles|user@domain.com
            */
            string prefix = "i:0#.w|";

            SPUser user = web.AllUsers[prefix + loginName];
            return user;
        }
        #endregion
    }
}
